package com.wy.order.service.impl;

import com.wy.order.dataobject.ProductCategory;
import com.wy.order.dataobject.ProductInfo;
import com.wy.order.dto.CarDTO;
import com.wy.order.enums.ProductInfoEnum;
import com.wy.order.enums.ResultEnum;
import com.wy.order.exception.MyException;
import com.wy.order.repository.ProductInfoRepository;
import com.wy.order.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;


@Service
public class ProductInfoServiceImpl implements ProductInfoService {

    @Autowired
    private ProductInfoRepository repository;

    @Override
    public ProductInfo findOne(String productId) {
        ProductInfo productInfo = new ProductInfo();
        productInfo.setProductId(productId);
        Example<ProductInfo> example = Example.of(productInfo);
        Optional<ProductInfo> optional = repository.findOne(example);
        if (optional.isPresent()) {
            productInfo = optional.get();
        }
        return productInfo;
    }


    @Override
    public List<ProductInfo> findUpAll() {
        return repository.findByProductState(ProductInfoEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return repository.save(productInfo);
    }

    @Override
    @Transactional
    public void increaseStock(List<CarDTO> carDTOList) {

        for (CarDTO carDTO : carDTOList
        ) {
            Optional<ProductInfo> optionalCarDTO = repository.findById(carDTO.getProductId());
            if (optionalCarDTO.isPresent()) {
                ProductInfo productInfo = optionalCarDTO.get();
                int in = productInfo.getProductStock() + carDTO.getProductQuantity();
                productInfo.setProductStock(in);
                repository.save(productInfo);
            }else {
                throw new MyException(ResultEnum.PRODUCT_NOT_EXIST);
            }

        }
    }

    @Override
    @Transactional
    public void decreaseStock(List<CarDTO> carDTOList) {

        for (CarDTO carDTO : carDTOList) {
            ProductInfo productInfo = this.findOne(carDTO.getProductId());

            int in = productInfo.getProductStock() - carDTO.getProductQuantity();
            if (in < 0) {
                throw new MyException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            productInfo.setProductStock(in);

            this.save(productInfo);
        }
    }
}
